package com.styytech.dadabao.api.requestresult;

import android.content.Context;

import com.styytech.dadabao.api.operations.UserOperations;
import com.styytech.dadabao.api.response.AbstractResponseResult;
import com.styytech.dadabao.utils.SpUser;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by user on 2015/8/3.
 */
public class LogResult extends RequestResult implements
        UserOperations {
    private Context context;

    /**
     * 构造函数
     *
     * @param httpResponseResult
     */
    public LogResult(AbstractResponseResult httpResponseResult, Context context) {
        super(httpResponseResult);
        this.context = context;
    }

    @Override
    public void doBusiness() {
        super.doBusiness();
        if (super.isSuccess()) {
            dataParse((JSONArray) super.getRows());
        }
    }


    private void dataParse(JSONArray jsonArray) {
        String token = null;
        if (jsonArray != null && !jsonArray.isNull(0)) {
            try {
                JSONObject json = jsonArray.getJSONObject(0);
                token = json.has("token") ? json.getString("token") : null;
                setToken(token);
            } catch (JSONException e) {
                e.printStackTrace();
                if (httpResponseResult != null) {
                    httpResponseResult.executeError("登陆失败",
                            AbstractResponseResult.RESPONSE_DATA_FORMAT_ERROR);
                }

            }
        }
        if (httpResponseResult != null) {
            httpResponseResult.executeSuccess(token);
        }
    }

    @Override
    public void setTokens(String paramString, int idCardVStatus, int payPasswordVStatus, int cardVStatus, int mobileVStatus, String phone, String realName) {

    }

    /**
     * 存储token
     *
     * @param token
     */
    @Override
    public void setToken(String token) {
        SpUser.setUserToken(context, token);
    }
}
